<template>
    <ul class="list">
       <li 
            class="item"  
            v-for='item of letters' 
            :key='item' 
            :ref='item'
            @touchstart='handleTouchStart'
            @touchmove='handleTouchMove'
            @touchend='handleTouchEnd'
            @click="handleLetterClick"
        >
            {{item}}
        </li>
    </ul> 
</template>
<script>
export default {
    name: 'CityAlphabet',
    props: {
        cities: Object
    },
    data(){
        //设置标识位
        return {
            touchStatus: false,
            startY: 0,
            // 节流
            timer: null 
        }
    },
    updated() {
        this.startY = this.$refs['A'][0].offsetTop
    },
    computed: {
        letters(){
            const letters = []
            for(let i in this.cities){
                letters.push(i)
            }
            //返回的结果大概是['A','B','C']
            return letters 
        }
    },
    methods: {
        // 当接收到点击事件的时候，会传递一个e对象(拿到一个事件对象)
        handleLetterClick(e){
            // 第一个是传递事件，第二个是事件传递的内容
            this.$emit('change', e.target.innerText)
            // console.log(e.target.innerText);//获取到字母
            
        },

        // 拖拽效果  当手滑动时
        handleTouchStart(){
            this.touchStatus = true
        },
        // 设置timer可以大大减少这个函数的执行，从而提高网页执行性能
        handleTouchMove(e){
            if(this.touchStatus){
                if(this.timer){
                    clearTimeout(this.timer)
                }
                this.timer = setTimeout(()=>{
                    //ffsetTop获取到顶部的距离
                    // const startY = this.$refs['A'][0].offsetTop
                    const touchY = e.touches[0].clientY - 79
                    const index = Math.floor((touchY - this.startY) / 20)
                    // console.log(index)
                    // 手指触摸屏幕，显示所有对应的点击位置
                    if(index >= 0 && index < this.letters.length){
                        this.$emit('change', this.letters[index])
                    }
                }, 16)
            }
        },
        handleTouchEnd(){
            this.touchStatus = false
        }
    }
}
</script>

<style lang='stylus' scoped>
    @import '~styles/varibles.styl'
    .list
        display flex
        flex-direction column
        justify-content  center
        position absolute
        top 1.76rem
        right 0
        bottom 0
        width .4rem
        .item
            text-align center
            color $bgColor
            line-height .4rem

</style>


